<template>
  <section class="myForm">
    <el-dialog :title="title" :visible="dialogVisible" :before-close="handleClose">
      <div class="form-tip" v-text="'温馨提示:目前设备影子属性只能新增和编辑已有的，不能清空已有的'"></div>
      <el-form :model="form" :rules="shadowRules" ref="validateFrom" autoComplete="on" label-width="120px">
        <el-form-item label="reported" prop="reported">
          <el-input type="textarea" v-model="form.reported" rows="5" placeholder='JSON格式对象，注意双引号包裹key-value，例如：{"color":"red"}'></el-input>
        </el-form-item>
        <el-form-item label="desired" prop="desired">
          <el-input type="textarea" v-model="form.desired" rows="5" placeholder='JSON格式对象，注意双引号包裹key-value，例如：{"number":"7"}'></el-input>
          {{formInfo}}
        </el-form-item>
        <div class="dialog-footer">
          <el-button @click="dialogStatus = false">取 消</el-button>
          <el-button type="primary" @click.native.prevent="submitForm">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>
  </section>
</template>

<script>
  import { Vue, Component, Prop, Watch } from 'vue-property-decorator'

  @Component
  export default class DeviceShadeTemplate extends Vue {
    @Prop({
      type: Boolean
    }) dialogVisible;
    @Prop({
      type: String
    }) title;
    @Prop({
      type: Object,
      default: () => {}
    }) info;
    data() {
      return {
        form: {
          desired: "",
          reported: ""
        },
        dialogStatus: this.dialogVisible, //表单是否显示状态
        shadowRules: { //表单rules规则
          reported: [{ required: true, trigger: 'blur', message: '请输入reported对象值' }],
          desired: [{ required: true, trigger: 'blur', message: '请输入desired对象值' }]
        }
      }
    }
    get formInfo() {
      if (Object.keys(this.info).length && this.info.shadow) {
        let shadowInfo = JSON.parse(this.info.shadow).state;
        this.$set(this.form, 'reported', JSON.stringify(shadowInfo.reported));
        this.$set(this.form, 'desired', JSON.stringify(shadowInfo.desired));
      }
    }
    @Watch('dialogVisible')
    dialogVisibleChange(val) { //监听dialogVisible改变Status
      this.dialogStatus = val
    }
    @Watch('dialogStatus')
    dialogStatusChange(val) { //关闭的时候触发表单清空
      this.$emit('update:dialogVisible', val)
    }
    handleClose(done) { //右上角关闭
      this.$confirm('确认关闭？')
        .then(_ => {
          this.dialogStatus = false
          done()
        })
        .catch(_ => {})
    }
    submitForm() { //回调父组件方法
      this.$refs.validateFrom.validate((valid) => {
        if (valid) {
          this.$emit('submitForm', this.form)
        } else {
          return false;
        }
      });
    }
  }
</script>

<style lang="scss" scoped>
  @import '~@scss/theme/form.scss';

  .el-textarea {
    max-width: 300px;
  }
</style>
